package com.tjut.core.utils;

import okhttp3.OkHttpClient;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.IOException;
import java.io.InputStream;

public class SaltUtil {

    private static final OkHttpClient client = new OkHttpClient().newBuilder()
            .followRedirects(false)  //禁止OkHttp的重定向操作，我们自己处理重定向
            .build();
    private static final ScriptEngineManager manager;

    private static final ScriptEngine engine;
    private static String reader;

    /**
     * 在这个方法中将js引擎初始化，为后面获取加密后的密码做准备。
     */
    static {
        manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
        ClassLoader classLoader = SaltUtil.class.getClassLoader();
        try (InputStream inputStream = classLoader.getResourceAsStream("static/key.js");) {
            int ch;
            StringBuilder sb = new StringBuilder();
            if (inputStream != null) {
                while ((ch = inputStream.read()) != -1)
                    sb.append((char) ch);
            }
            reader = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取加密后的密码
     *
     * @param password 原始密码
     * @param slat     盐
     * @return
     * @throws Exception
     */
    public static String getPassword(String password, String slat) throws Exception {
        engine.eval(reader);
        if (engine instanceof Invocable) {
            Invocable invoke = (Invocable) engine;    // 调用merge方法，并传入两个参数
            return (String) invoke.invokeFunction("_ep", password, slat);
        }
        return "";
    }

}
